package com.lqian.share;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class T_AtomicStampedReference_05 {
    private static AtomicInteger index = new AtomicInteger(10);

    static AtomicStampedReference<Integer> stampedRef = new AtomicStampedReference<>(10,1);

    public static void main(String[] args) {
        new Thread(()->{
            int stamp = stampedRef.getStamp();

            System.out.println(Thread.currentThread().getName() + " The First Version:" +stamp);
            // opt
            stampedRef.compareAndSet(10,11,
                    stampedRef.getStamp(),stampedRef.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + " The Second Version:" +stampedRef.getStamp());

            stampedRef.compareAndSet(11,10,
                    stampedRef.getStamp(),stampedRef.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + " The Third Version:" +stampedRef.getStamp());
        },"Kimi ==>").start();

        new Thread(()->{
            System.out.println("-----");
            int stamp = stampedRef.getStamp();

            System.out.println(Thread.currentThread().getName() + " The First Version:" +stamp);
            try {
                TimeUnit.SECONDS.sleep(3);
                boolean isSuccess = stampedRef.compareAndSet(10, 12,
                        stampedRef.getStamp(), stampedRef.getStamp() + 1);
                // version 1.0
                // version 2.0
                // version 3.0
                // cas
                System.out.println(Thread.currentThread().getName() + " Whether the modification is successful: " +isSuccess
                +", current version : " + stampedRef.getStamp());
                System.out.println(Thread.currentThread().getName() +" Current actual value : "+stampedRef.getReference() );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Marry ==>").start();
    }

}
